package csv

import (
	"fmt"
	"os"
	"time"
)

func Save(fileName string, head string, lines []string) error {
	file, err := os.Create(fileName)
	if err != nil {
		fmt.Println("create file failed.", fileName)
	}
	defer file.Close()

	// 写入CSV标题（使用UTF-8 BOM确保中文兼容）
	file.WriteString("\xEF\xBB\xBF") // UTF-8 BOM
	if head != "" {
		file.WriteString(head)
		file.WriteString("\n")
	}

	for _, line := range lines {
		file.WriteString(line)
		file.WriteString("\n")
	}
	return nil
}

func SaveArray(fileName string, head string, array [][]interface{}) {
	var lines []string
	for _, row := range array {
		var line string
		for _, v := range row {
			line += fmt.Sprintf("%s,%T,", v, v)
		}
		if len(line) > 1 {
			r := []rune(line)
			line = string(r[:len(r)-1])
		}
		lines = append(lines, line)
	}
	Save(fileName, head, lines)
}

func GetDate20060102() string {
	return time.Now().Format("20060102")
}
